package cn.monkey.chat.server.connect.chat.state.group;

import cn.monkey.chat.server.connect.chat.ChatExchange;
import cn.monkey.chat.server.connect.chat.data.ClientExchangePkgPair;
import cn.monkey.chat.server.proto.Command;
import cn.monkey.chat.server.proto.Package;
import cn.monkey.state.core.OncePerInitState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.function.Supplier;

public class ChatState extends OncePerInitState {

    private static final Logger log = LoggerFactory.getLogger(ChatState.class);

    public static final String CODE = "chat";

    public ChatState(ChatGroup chatGroup) {
        super(CODE, chatGroup);
    }

    @Override
    public ChatContext getStateContext() {
        return (ChatContext) super.getStateContext();
    }

    @Override
    protected void onInit(Supplier<Long> supplier) {

    }

    @Override
    public void fireEvent(Supplier<Long> timer, Object event) throws Exception {
        if (event instanceof ClientExchangePkgPair(var exchange, var pkg)) {
            String cmdType = pkg.getCmdType();
            if (Command.CHAT.equals(cmdType)) {
                this.onChat(exchange, pkg);
                return;
            }
            switch (cmdType) {
                case Command.CLICK_OUT -> this.onClickOut(exchange, pkg);
                case Command.ONLINE -> this.onLine(exchange, pkg);
            }
        }
    }

    private void onLine(ChatExchange exchange, Package pkg) {
        ChatContext stateContext = this.getStateContext();
        stateContext.add(exchange);
    }

    private void onClickOut(ChatExchange exchange, Package pkg) {

    }

    private void onChat(ChatExchange exchange, Package pkg) {
        ChatContext stateContext = this.getStateContext();
        Collection<ChatExchange> allExchange = stateContext.getAllExchange();
        for (ChatExchange chatExchange : allExchange) {
            if (exchange.id().equals(chatExchange.id())) {
                continue;
            }
            chatExchange.writeAndFlush(pkg);
        }
        stateContext.addMessage(pkg);

        // TODO ack确认包
        exchange.writeAndFlush(pkg);
    }

    @Override
    public String finish(Supplier<Long> supplier) throws Exception {
        return "";
    }
}
